<?php
namespace app\service;

use app\model\GoodsPeriodModel;
use app\model\OrderBillDetailsModel;
use app\model\OrderBillModel;
use app\model\OrderDistributionModel;
use app\model\OrderModel;
use app\model\OrderPeriodProcessModel;
use app\model\OrderProfitProcessModel;
use support\Db;
use support\facade\Logger;
use Webman\RedisQueue\Client;
use const support\AUTO_CONFIRM_ORDER_PROFIT_QUEUE;
use const support\AUTO_HANDLE_ORDER_PROFIT_QUEUE;
use const support\CORRECT;
use const support\DENY;
use const support\order_status_8;

class OrderBillService{

    //生成对账单
    public static function createOrderBill(): bool
    {
        //本次日志关联标识
        $logId=md5(uniqid('ct'));
        //获取昨日0点时间戳
        $time=strtotime("yesterday midnight");
        Logger::app(sprintf('生成对账单(%s):获取昨日0点时间戳',$logId),'info',[$time]);
        //获取符合营期ID
        $goodsPeriodIds=GoodsPeriodModel::where([
            'goods_period_date'=>$time,
            'status'           =>CORRECT
        ])->pluck('id')->toArray();
        //检测成团营期
        $goodsPeriodIds=OrderPeriodProcessModel::whereIn('goods_period_id',$goodsPeriodIds)
            ->where('status',CORRECT)->pluck('goods_period_id')->toArray();
        if (!$goodsPeriodIds){
            Logger::app(sprintf('生成对账单(%s):未检测到成团信息',$logId),'info',[$time]);
            return true;
        }
        //查询符合此时间结算订单
        $orderIds=OrderModel::where([
            'order_status'      =>order_status_8,
            'is_verification'   =>CORRECT,
            'is_allow_profit'   =>CORRECT,
            'is_profit'         =>DENY,
            'status'            =>CORRECT,
            'is_bill'           =>DENY,
        ])->whereIn('goods_period_id',$goodsPeriodIds)->pluck('id')->toArray();
        Logger::app(sprintf('生成对账单(%s):获取符合对账订单组',$logId),'info',$orderIds);
        if (empty($orderIds)){
            return true;
        }
        //计算本次总账期金额
        $orderRevenues=OrderDistributionModel::whereIn('order_id',$orderIds)->where('status',CORRECT)->pluck('order_revenue_amount','order_id')->toArray();
        $orderReceipts=OrderDistributionModel::whereIn('order_id',$orderIds)->where('status',CORRECT)->pluck('order_receipt_amount','order_id')->toArray();
         //计算总收益金额
        $orderTotalRevenueAmount=$orderRevenues?array_sum(array_values($orderRevenues)):0;
        //计算总收款额
        $orderTotalReceiptAmount=$orderReceipts?array_sum(array_values($orderReceipts)):0;
        //出账单
        $billPeriod=substr(date('Ymd'),2);
        Db::beginTransaction();
        try {
            $billInsert=[
                'bill_sn'       =>createOrderSn(),
                'bill_period'   =>$billPeriod,
                'bill_amount'   =>$orderTotalReceiptAmount,
                'commission_amount'=>$orderTotalRevenueAmount,
                'settlement_amount'=>$orderTotalReceiptAmount-$orderTotalRevenueAmount,
                'bill_order_num'=>count($orderIds),
                'is_audit'      =>CORRECT,
                'create_time'   =>time()
            ];
            Logger::app(sprintf('生成对账单(%s):创建账单数据',$logId),'info',$billInsert);
            //创建账单
            $billId=OrderBillModel::insertGetId($billInsert);
            if (!$billId){
                Db::rollBack();
                Logger::app(sprintf('生成对账单(%s):创建账单失败',$logId));
                return false;
            }
            //添加账单详情
            $orderBillDetailsInserts=[];
            foreach ($orderIds as $orderId){
                $orderAmount=$orderReceipts[$orderId]??0;
                $commissionAmount=$orderRevenues[$orderId]??0;
                $orderBillDetailsInserts[]=[
                    'order_id'=>$orderId,
                    'bill_id' =>$billId,
                    'order_amount'=>$orderAmount,
                    'commission_amount'=>$commissionAmount,
                    'settlement_amount'=>$orderAmount-$commissionAmount,
                    'create_time'=>time()
                ];
                Logger::app(sprintf('生成对账单(%s):添加账单详情数据',$logId),'info',$orderBillDetailsInserts);
                //增加分账进程控制
                $ret=OrderBillDetailsModel::insert($orderBillDetailsInserts);
                if (!$ret){
                    Db::rollBack();
                    Logger::app(sprintf('生成对账单(%s):添加账单详情信息失败',$logId));
                    return false;
                }
            }
            //批量更新订单状态
            $ret=OrderModel::whereIn('id',$orderIds)->update([
                'is_bill'           =>CORRECT,
                'update_time'       =>time()
            ]);
            if (!$ret){
                Db::rollBack();
                Logger::app(sprintf('生成对账单(%s):批量更新订单状态失败',$logId));
                return false;
            }
            Db::commit();
            Logger::app(sprintf('生成对账单(%s):成功',$logId));
            return true;
        } catch (\Throwable $e) {
            Db::rollBack();
            Logger::app($e);
            return false;
        }
    }

    //确认分账操作
    public static function confirmOrderProfit(){
        //检测当前符合分账的订单账单
        $orderBillIds=OrderBillModel::where([
            'is_audit'          =>2,
            'status'            =>CORRECT,
            'transfer_status'   =>1
        ])->pluck('id')->toArray();
        Logger::app('确认分账操作:符合分账账单ID组','info',$orderBillIds);
        foreach ($orderBillIds as $orderBillId){
            //批量获取账单下的订单ID组
            $orderIds=OrderBillDetailsModel::where([
                'bill_id'=>$orderBillId,
                'status' =>CORRECT
            ])->pluck('order_id')->toArray();
            Logger::app('确认分账操作:符合分账订单ID组','info',$orderIds);
            //发送入队列执行
            foreach ($orderIds as $orderId){
                Client::send(AUTO_CONFIRM_ORDER_PROFIT_QUEUE, ['order_id'=>$orderId], 5);
            }
        }
    }

}
